package cn.yuitstyle.fss.minio.demo.controller;

import cn.hutool.core.io.IoUtil;
import cn.yuitstyle.fss.minio.starter.config.MinioConfig;
import cn.yuitstyle.fss.minio.starter.util.MinioFileService;
import com.sun.javafx.fxml.builder.URLBuilder;
import io.minio.ObjectWriteResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;

/**
 * @author yuwg
 */
@RestController
@Slf4j
public class MinioController {

    @Autowired
    private MinioFileService minioFileService;
    @Autowired
    private MinioConfig minioConfig;


    @PostMapping("/upload")
    public String upload(MultipartFile file) {
        try {
            String fileName = file.getOriginalFilename();
            String contentType = file.getContentType();
            ObjectWriteResponse objectWriteResponse = minioFileService.uploadMultipartFile(minioConfig.getBucketName(), file, fileName, contentType);
            String object = objectWriteResponse.object();

            String presignedObjectUrl = minioFileService.getPresignedObjectUrl(minioConfig.getBucketName(), object);
            presignedObjectUrl = presignedObjectUrl.substring(0, presignedObjectUrl.lastIndexOf("?"));
            return presignedObjectUrl;
        } catch (Exception e) {
            log.error(e.getMessage());
            return "上传失败";
        }
    }

    @DeleteMapping("/")
    public String delete(@RequestParam("fileName") String fileName) {
        try {

            minioFileService.removeFile(minioConfig.getBucketName(), fileName);
        } catch (Exception e) {
            return e.getMessage();
        }
        return "success";
    }

    @GetMapping("/info")
    public String info(@RequestParam("fileName") String fileName) {
        return minioFileService.getFileStatusInfo(minioConfig.getBucketName(), fileName);
    }

    @GetMapping("/url")
    public String url(@RequestParam("fileName") String fileName) {
        return minioFileService.getPresignedObjectUrl(minioConfig.getBucketName(), fileName);
    }

    @GetMapping("/download")
    public void download(@RequestParam("fileName") String fileName, HttpServletResponse response) {
        try {
            InputStream is = minioFileService.getObject(minioConfig.getBucketName(), fileName);
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.setContentType("application/force-stream");
            response.setCharacterEncoding("utf-8");
            IoUtil.copy(is, response.getOutputStream());
        } catch (Exception e) {
            log.error(e.getMessage());
        }
    }
}
